package com.halfsword.creativecraft.gui.machine;

import com.halfsword.creativecraft.block.BlockLoader;
import com.halfsword.creativecraft.block.custom.machine.blockentity.SpaceShardCollectorMachineBlockEntity;
import com.halfsword.creativecraft.gui.MenuTypes;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.*;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraftforge.common.capabilities.ForgeCapabilities;
import net.minecraftforge.items.SlotItemHandler;

/**
 * 空间碎片收集器容器菜单
 */
public class SpaceCollectorMenu extends AbstractContainerMenu {

    // 核心成员
    public final SpaceShardCollectorMachineBlockEntity blockEntity;
    private final Level level;
    private final ContainerData data;

    // 槽位常量
    private static final int HOTBAR_SLOT_COUNT = 9;
    private static final int PLAYER_INVENTORY_ROW_COUNT = 3;
    private static final int PLAYER_INVENTORY_COLUMN_COUNT = 9;
    private static final int PLAYER_INVENTORY_SLOT_COUNT = PLAYER_INVENTORY_COLUMN_COUNT * PLAYER_INVENTORY_ROW_COUNT;
    private static final int VANILLA_SLOT_COUNT = HOTBAR_SLOT_COUNT + PLAYER_INVENTORY_SLOT_COUNT;
    private static final int VANILLA_FIRST_SLOT_INDEX = 0;
    private static final int TE_INVENTORY_FIRST_SLOT_INDEX = VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT;
    private static final int TE_INVENTORY_SLOT_COUNT = 6;

    // ================ 构造函数 ================
    public SpaceCollectorMenu(int containerId, Inventory inv, FriendlyByteBuf extraData) {
        this(
                containerId,
                inv,
                inv.player.level().getBlockEntity(extraData.readBlockPos()),
                new SimpleContainerData(2) // 只需要2个数据字段：进度和最大进度
        );
    }

    public SpaceCollectorMenu(int containerId, Inventory inv, BlockEntity entity, ContainerData data) {
        super(MenuTypes.SPACE_COLLECTOR_MENU.get(), containerId);
        checkContainerSize(inv, TE_INVENTORY_SLOT_COUNT);

        blockEntity = (SpaceShardCollectorMachineBlockEntity) entity;
        this.level = inv.player.level();
        this.data = data;

        addPlayerInventory(inv);
        addPlayerHotBar(inv);

        this.blockEntity.getCapability(ForgeCapabilities.ITEM_HANDLER).ifPresent(handler -> {
            // 输入槽位
            this.addSlot(new SlotItemHandler(handler, 0, 27, 8));   // 左上
            this.addSlot(new SlotItemHandler(handler, 1, 27, 59));  // 左下
            this.addSlot(new SlotItemHandler(handler, 2, 57, 16));  // 中上
            this.addSlot(new SlotItemHandler(handler, 3, 57, 52));  // 中下

            // 输出槽位
            this.addSlot(new SlotItemHandler(handler, 4, 126, 12)); // 右上输出
            this.addSlot(new SlotItemHandler(handler, 5, 126, 58)); // 右下输出
        });

        addDataSlots(data);
    }

    // ================ 快速移动物品 ================
    @Override
    public ItemStack quickMoveStack(Player player, int index) {
        ItemStack itemstack = ItemStack.EMPTY;
        Slot slot = this.slots.get(index);

        if (slot != null && slot.hasItem()) {
            ItemStack itemstack1 = slot.getItem();
            itemstack = itemstack1.copy();

            if (index < VANILLA_SLOT_COUNT) {
                // 从玩家物品栏转移到机器
                if (!this.moveItemStackTo(itemstack1, TE_INVENTORY_FIRST_SLOT_INDEX,
                        TE_INVENTORY_FIRST_SLOT_INDEX + TE_INVENTORY_SLOT_COUNT, false)) {
                    return ItemStack.EMPTY;
                }
            } else if (index < TE_INVENTORY_FIRST_SLOT_INDEX + TE_INVENTORY_SLOT_COUNT) {
                // 从机器转移到玩家物品栏
                if (!this.moveItemStackTo(itemstack1, VANILLA_FIRST_SLOT_INDEX,
                        VANILLA_FIRST_SLOT_INDEX + VANILLA_SLOT_COUNT, false)) {
                    return ItemStack.EMPTY;
                }
            }

            if (itemstack1.isEmpty()) {
                slot.set(ItemStack.EMPTY);
            } else {
                slot.setChanged();
            }

            if (itemstack1.getCount() == itemstack.getCount()) {
                return ItemStack.EMPTY;
            }

            slot.onTake(player, itemstack1);
        }

        return itemstack;
    }

    // ================ 容器验证 ================
    @Override
    public boolean stillValid(Player player) {
        return stillValid(
                ContainerLevelAccess.create(level, blockEntity.getBlockPos()),
                player,
                BlockLoader.SPACE_SHARD_COLLECTOR_MACHINE.get()
        );
    }

    // ================ 玩家物品栏添加 ================
    private void addPlayerInventory(Inventory playerInventory) {
        for (int row = 0; row < PLAYER_INVENTORY_ROW_COUNT; ++row) {
            for (int column = 0; column < PLAYER_INVENTORY_COLUMN_COUNT; ++column) {
                this.addSlot(
                        new Slot(
                                playerInventory,
                                column + row * 9 + 9,
                                9 + column * 18,
                                83 + row * 18
                        )
                );
            }
        }
    }
    public int getProgress() {
        return data.get(0); // 进度值
    }

    public int getMaxProgress() {
        return data.get(1); // 最大进度值
    }

    private void addPlayerHotBar(Inventory playerInventory) {
        for (int i = 0; i < HOTBAR_SLOT_COUNT; ++i) {
            this.addSlot(
                    new Slot(
                            playerInventory,
                            i,
                            9 + i * 18,
                            141
                    )
            );
        }
    }

    // ================ 进度条数据 ================
    public boolean isCrafting() {
        return data.get(0) > 0; // 索引0存储当前进度
    }

    /**
     * 获取进度百分比（0.0 - 1.0）
     */
    public float getProgressPercent() {
        int progress = this.data.get(0);      // 当前进度
        int maxProgress = this.data.get(1);   // 最大进度（索引1）

        if (maxProgress > 0 && progress > 0) {
            return (float) progress / maxProgress;
        }
        return 0f;
    }
}